<template>
  <div class="tree-list-container">
    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="120px" @submit.prevent="handleSearch">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="中文名">
              <el-input v-model="searchForm.chineseName" placeholder="请输入中文名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科名">
              <el-input v-model="searchForm.familyName" placeholder="请输入科名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="属名">
              <el-input v-model="searchForm.genusName" placeholder="请输入属名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="树龄">
              <el-input-number v-model="searchForm.estimatedAge" :min="0" placeholder="请输入树龄" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地理位置">
              <el-input v-model="searchForm.locationAddress" placeholder="请输入地理位置" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="健康状态">
              <el-select v-model="searchForm.status" placeholder="请选择健康状态" clearable>
                <el-option label="异常" :value="0" />
                <el-option label="健康" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="创建时间起">
              <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder="请选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间止">
              <el-date-picker v-model="searchForm.endTime" type="datetime" placeholder="请选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" class="text-right">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格操作按钮 -->
    <div class="table-actions">
      <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除 ({{ selectedRows.length }})
      </el-button>
    </div>

    <!-- 古树信息表格 -->
    <el-card class="table-card">
      <el-table :data="treeData" border style="width: 100%" v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="treeId" label="ID" width="80" />
        <el-table-column prop="chineseName" label="中文名" min-width="120" />
        <el-table-column prop="scientificName" label="拉丁学名" min-width="150" />
        <el-table-column prop="familyName" label="科名" width="100" />
        <el-table-column prop="genusName" label="属名" width="100" />
        <el-table-column prop="estimatedAge" label="树龄(年)" width="100" />
        <el-table-column prop="protectionLevel" label="保护等级" width="100">
          <template #default="scope">
            <el-tag :type="getProtectionLevelTag(scope.row.protectionLevel)">
              {{ getProtectionLevelText(scope.row.protectionLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gpsLongitude" label="经度" width="120" />
        <el-table-column prop="gpsLatitude" label="纬度" width="120" />
        <el-table-column prop="locationAddress" label="地理位置" min-width="200" />
        <el-table-column prop="qrCodeUrl" label="二维码" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.qrCodeUrl" :src="scope.row.qrCodeUrl" style="width: 40px; height: 40px"
              :preview-src-list="[scope.row.qrCodeUrl]" fit="contain" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="健康状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '健康' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
       <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editTree(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="deleteTree(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="古树详情" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ detailData.treeId }}</el-descriptions-item>
        <el-descriptions-item label="中文名">{{ detailData.chineseName }}</el-descriptions-item>
        <el-descriptions-item label="拉丁学名">{{ detailData.scientificName }}</el-descriptions-item>
        <el-descriptions-item label="科名">{{ detailData.familyName }}</el-descriptions-item>
        <el-descriptions-item label="属名">{{ detailData.genusName }}</el-descriptions-item>
        <el-descriptions-item label="树龄">{{ detailData.estimatedAge }}年</el-descriptions-item>
        <el-descriptions-item label="保护等级">
          {{ getProtectionLevelText(detailData.protectionLevel) }}
        </el-descriptions-item>
        <el-descriptions-item label="经度">{{ detailData.gpsLongitude }}</el-descriptions-item>
        <el-descriptions-item label="纬度">{{ detailData.gpsLatitude }}</el-descriptions-item>
        <el-descriptions-item label="地理位置" :span="2">{{ detailData.locationAddress }}</el-descriptions-item>
        <el-descriptions-item label="健康状态">
          <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
            {{ detailData.status === 1 ? '健康' : '异常' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="二维码">
          <el-image v-if="detailData.qrCodeUrl" :src="detailData.qrCodeUrl" style="width: 100px; height: 100px"
            :preview-src-list="[detailData.qrCodeUrl]" />
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ detailData.description || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editForm.treeId ? '修改古树信息' : '新增古树信息'" width="60%">
      <el-form :model="editForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中文名" prop="chineseName"
              :rules="[{ required: true, message: '请输入中文名', trigger: 'blur' }]">
              <el-input v-model="editForm.chineseName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拉丁学名" prop="scientificName">
              <el-input v-model="editForm.scientificName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科名" prop="familyName" :rules="[{ required: true, message: '请输入科名', trigger: 'blur' }]">
              <el-input v-model="editForm.familyName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属名" prop="genusName" :rules="[{ required: true, message: '请输入属名', trigger: 'blur' }]">
              <el-input v-model="editForm.genusName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="树龄" prop="estimatedAge">
              <el-input-number v-model="editForm.estimatedAge" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保护等级" prop="protectionLevel">
              <el-select v-model="editForm.protectionLevel" placeholder="请选择保护等级">
                <el-option label="一级保护" :value="1" />
                <el-option label="二级保护" :value="2" />
                <el-option label="三级保护" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="gpsLongitude">
              <el-input-number v-model="editForm.gpsLongitude" :precision="7" :step="0.0000001" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="gpsLatitude">
              <el-input-number v-model="editForm.gpsLatitude" :precision="7" :step="0.0000001" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="健康状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择健康状态">
                <el-option label="异常" :value="0" />
                <el-option label="健康" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二维码URL" prop="qrCodeUrl">
              <el-input v-model="editForm.qrCodeUrl" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地理位置" prop="locationAddress"
          :rules="[{ required: true, message: '请输入地理位置', trigger: 'blur' }]">
          <el-input v-model="editForm.locationAddress" type="textarea" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTree">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTreeList, deleteTrees } from '@/apis/treeAPI'

// 查询表单数据
const searchForm = reactive({
  chineseName: '',
  familyName: '',
  genusName: '',
  estimatedAge: null,
  locationAddress: '',
  status: null,
  startTime: '',
  endTime: ''
})

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const treeData = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const detailData = ref({})
const selectedRows = ref([])

// 编辑表单数据
const editForm = reactive({
  treeId: null,
  chineseName: '',
  scientificName: '',
  familyName: '',
  genusName: '',
  estimatedAge: null,
  protectionLevel: 3,
  gpsLongitude: null,
  gpsLatitude: null,
  locationAddress: '',
  qrCodeUrl: '',
  status: 1,
  description: ''
})

// 获取保护等级文本
const getProtectionLevelText = (level) => {
  const levels = {
    1: '一级保护',
    2: '二级保护',
    3: '三级保护'
  }
  return levels[level] || '未知等级'
}

// 获取保护等级标签类型
const getProtectionLevelTag = (level) => {
  const types = {
    1: 'danger',
    2: 'warning',
    3: 'success'
  }
  return types[level] || 'info'
}

// 查询方法
const handleSearch = () => {
  pagination.pageNum = 1
  fetchTreeList()
}

// 重置查询条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.pageNum = 1
  fetchTreeList()
}

// 处理分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  fetchTreeList()
}

// 处理当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchTreeList()
}

// 处理表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的古树')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条古树信息吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 执行批量删除逻辑
    const ids = selectedRows.value.map(item => item.treeId)
    performDeleteByIds(ids)
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 查看详情
const viewDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 编辑古树
const editTree = (row) => {
  Object.assign(editForm, row)
  editDialogVisible.value = true
}

// 删除古树
const deleteTree = (row) => {
  ElMessageBox.confirm(
    `确定要删除古树 "${row.chineseName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 执行删除逻辑，传递单个ID的数组
    performDeleteByIds([row.treeId])
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 通过ID数组执行删除操作
const performDeleteByIds = async (ids) => {
  try {
    console.log('ids:',ids)
    const result = await deleteTrees(ids)
    if (result.code === 1) {
      ElMessage.success(`成功删除 ${ids.length} 条记录`)
      // 如果当前页数据被删完，返回上一页
      if (treeData.value.length === ids.length && pagination.pageNum > 1) {
        pagination.pageNum--
      }
      fetchTreeList()
    }
    if(result.code===0){
      ElMessage.error('删除失败')
    }
  } catch (error) {
    ElMessage.error()
    console.error(error)
  }
}

// 保存古树信息
const saveTree = () => {
  // 这里应该执行保存逻辑
  ElMessage.success(editForm.treeId ? '修改成功' : '新增成功')
  editDialogVisible.value = false
  fetchTreeList()
}

// 获取古树列表数据
const fetchTreeList = async () => {
  loading.value = true
  try {
    const result = await getTreeList({
      ...searchForm,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    })
    treeData.value = result.data.records
    pagination.total = result.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchTreeList()
})
</script>

<style scoped>
.tree-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-actions {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>